package com.thx.tags;

import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.components.Component;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;

import com.opensymphony.xwork2.util.ValueStack;
import com.thx.common.util.AppContext;
import com.thx.common.util.StringUtil;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.WebConstant;


/**
 * 构建分页标签体的类.
 *
 * @author 牛慧敏
 */
public class Pages extends Component {

  private HttpServletRequest request;
  private String pageNo; // 当前页码
  private String total; // 总页数
  private String styleClass; // 分页的样式
  private String theme; // 分页的主题
  private String url; // action的路径
  private String urlType; // 路径的类型，主要用于URL重写的扩展
  private int hrefCount =
      StringUtil.string2Int(AppContext.getProperties(WebConstant.HREFCOUNT_PAGE_KEY), 8);// 最多显示的连接数
  private boolean hasPerPage;// --是否有每页几条的选项
  private boolean hasGoto;// 是否有跳转


  public Pages(ValueStack stack, HttpServletRequest request) {
    super(stack);
    this.request = request;
  }

  @Override
  public boolean end(Writer writer, String body) {
    boolean result = super.start(writer);
    try {
      // 从ValueStack中取出数值
      Object obj = this.getStack().findValue(pageNo);
      pageNo = String.valueOf((Integer) obj);
      obj = this.getStack().findValue(total);
      total = String.valueOf((Integer) obj);

      Map cont = this.getStack().getContext();
      StrutsRequestWrapper req = (StrutsRequestWrapper) cont.get(StrutsStatics.HTTP_REQUEST);
      if (StringUtils.isBlank(url)) {
        url = (String) req.getAttribute("pageTag.request_uri");
        if (StringUtils.isBlank(url)) {
          url = req.getRequestURI();
        }
      }
      String pageNoStr = "?pageNo=";
      if ("dir".equals(urlType)) { // 当url的类型为目录类型时，比如http://localhost:8090/yongtree/page/1
        pageNoStr = "";
        if ("1".equals(pageNo)) { // 第一页时
          if (url.lastIndexOf("/") != url.length() - 1) {
            if (url.lastIndexOf("1") == url.length() - 1) { // 如果有页码1，则去掉1
              url = url.substring(0, url.length() - 1);
            } else if (url.lastIndexOf("/") != url.length() - 1) { // 如果没有页码1，并且最后不是'/'时，加上'/'
              url = url + "/";
            }
          }
        } else {
          url = url.substring(0, url.lastIndexOf("/") + 1);
        }
      }

      // 下面这段处理主要是用来处理动态查询的参数，并拼接成url
      StringBuffer perUrl = new StringBuffer("");
      if (this.getParameters().size() != 0) {
        Iterator iter = this.getParameters().keySet().iterator();
        while (iter.hasNext()) {
          String key = (String) iter.next();
          Object val = this.getParameters().get(key);
          if(val!=null){
            val = URLEncoder.encode(val.toString(), "UTF-8");
          }
          perUrl.append("&").append(key).append("=").append(val);
        }
      }

      Integer cpageInt = Integer.valueOf(pageNo);

      StringBuilder str = new StringBuilder();
      str.append("<span ");
      str.append(" class='" + styleClass + "'>");

      int perPage = (Integer) ThreadLocalContext.get("perPage");
      /*
       * str.append("<script type=\"text/javascript\">"); //--页面的翻页方法绑定 str. append(
       * "$(\".themeText .thx-page-span\").click(function(){var href = $(this).attr(\"href\");" );
       * str.append("$(\".content-wrapper\").empty();$(document).jProgressbar.show();");
       * str.append("if(href){common.ajaxPage(href);}});");
       *
       * if(hasPerPage){ str.append(
       * "$(\".thx-modify-page\").click(function(){var href = $(this).attr(\"href\") +" +
       * "\"&perPage=\" $(this).val()\";");
       * str.append("$(\".content-wrapper\").empty();$(document).jProgressbar.show();");
       * str.append("if(href){common.ajaxPage(href);}});"); } if(hasGoto){ str.append(
       * "$(\".thx-goto-page\").click(function(){var href = $(this).attr(\"href\")+ " +
       * "&perPage=\" $(\"#tz\").val()\";");
       * str.append("$(\".content-wrapper\").empty();$(document).jProgressbar.show();");
       * str.append("if(href){common.ajaxPage(href);}});");
       *
       * } str.append("</script>");
       */
      /*
       * if(hasPerPage){ str.append("<label>每页"); str.append(
       * "<select class='thx-modify-page'  href='"+url+pageNoStr+"1"+perUrl+"'>");
       *
       * str.append("<option value='5'"); if(perPage==5){ str.append(" selected"); }
       * str.append(">5</option>"); str.append("<option value='10'"); if(perPage==10){ str.append(
       * " selected"); } str.append(">10</option>"); str.append("<option value='15'");
       * if(perPage==15){ str.append(" selected"); } str.append(">15</option></select> ");
       * str.append("条</label>"); }
       */


      // 文本样式
      if (theme == null || "text".equals(theme)) {
        // 当前页与总页数相等
        if (pageNo.equals(total)) {
          // 如果total = 1，则无需分页，显示“首页 上一页 下一页 末页”
          if ("1".equals(total)) {
            str.append("<span href=''><a href='#'>首页</a></span> ");
            str.append("<span href=''><a href='#'>上一页</a></span>");
            str.append("<span href=''><a href='#'>下一页 </a></span>");
            if (hasGoto) {
              str.append("<input value='" + pageNo + "' name='tz' id='tz' type='text'/>");
              str.append("<span class='thx-goto-page' href='" + url + '?' + "perPage=" + perPage
                  + perUrl + "'><a href='javascript:void(0);'>跳转 </a></span>");
            }
            str.append("<span href=''><a href='#'>末页 </a></span>");
            str.append("<font> 第" + pageNo + "/" + total + "页</font>");

          } else {
            // 到达最后一页,显示“[首页] [上一页] 下一页 末页”,“[]”代表<a>
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + "1" + perUrl
                + "'><a href='#'>首页</a></span> ");
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + (cpageInt - 1)
                + perUrl + "'><a href='#'>上一页</a></span>");
            str.append("<span href=''><a href='#'>下一页 </a></span>");
            if (hasGoto) {
              str.append("<input value='" + pageNo + "' name='tz' id='tz' type='text'/>");
              str.append("<span class='thx-goto-page' href='" + url + '?' + "perPage=" + perPage
                  + perUrl + "'><a href='javascript:void(0);'>跳转 </a></span>");
            }
            str.append("<span href=''><a href='#'>末页 </a></span>");
            str.append("<font> 第" + pageNo + "/" + total + "页</font>");
          }
        } else {
          // 当前页与总页数不相同
          if ("1".equals(pageNo)) {
            // 第一页，显示“首页 上一页 [下一页] [末页]”
            str.append("<span href=''><a href='#'>首页 </a></span>");
            str.append("<span href=''><a href='#'>上一页 </a></span>");
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + (cpageInt + 1)
                + perUrl + "'><a href='#'>下一页</a></span> ");
            if (hasGoto) {
              str.append("<input value='" + pageNo + "' name='tz' id='tz' type='text'/>");
              str.append("<span class='thx-goto-page' href='" + url + '?' + "perPage=" + perPage
                  + perUrl + "'><a href='javascript:void(0);'>跳转 </a></span>");
            }
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + total + perUrl
                + "'><a href='#'>末页</a></span>");
            str.append("<font> 第" + pageNo + "/" + total + "页</font>");
          } else {
            // 不是第一页，显示“[首页] [上一页] [下一页] [末页]”
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + "1" + perUrl
                + "'><a href='#'>首页</a></span>");
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + (cpageInt - 1)
                + perUrl + "'><a href='#'>上一页</a></span> ");
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + (cpageInt + 1)
                + perUrl + "'><a href='#'>下一页</a></span>");
            if (hasGoto) {
              str.append("<input value='" + pageNo + "' name='tz' id='tz' type='text'/>");
              str.append("<span class='thx-goto-page' href='" + url + '?' + "perPage=" + perPage
                  + perUrl + "'><a href='javascript:void(0);'>跳转 </a></span>");
            }
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + total + perUrl
                + "'><a href='#'>末页</a></span>");
            str.append("<font> 第" + pageNo + "/" + total + "页</font>");
          }
        }

      } else if ("number".equals(theme)) { // 数字样式 [1 2 3 4 5 6 7 8 9 10 > >>]
        Integer totalInt = Integer.valueOf(total);
        // 如果只有一页，则无需分页
        if (totalInt == 1) {
          str.append("<a  href='javascript:void(0);'><<</a> ");
          str.append("<a  href='javascript:void(0);'><</a> ");
          str.append(
              "<span class='thx-page-span'><a class='on' href='javascript:void(0);'>1</a></span>");
          str.append("<a  href='javascript:void(0);'>&nbsp;></a> ");
          str.append("<a  href='javascript:void(0);'>>></a> ");
        } else {
          if (cpageInt > 1) {
            // 当前不是第一组，要显示“<< <”
            // <<：返回前一组第一页
            // <：返回前一页
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + "1" + "&perPage="
                + perPage + perUrl + "'><a title='首页' href='#'><<</a></span> ");
            str.append("<span class='thx-page-span' href='" + url + pageNoStr + (cpageInt - 1)
                + "&perPage=" + perPage + perUrl + "'><a title='前一页' href='#'><</a></span> ");
          } else {
            str.append("<a  href='javascript:void(0);'><<</a> ");
            str.append("<a  href='javascript:void(0);'><</a> ");
          }

          int preCount = 0;
          int nextCount = 0;
          if (hrefCount % 2 == 0) {
            preCount = hrefCount / 2 - 1;
            nextCount = hrefCount / 2;
          } else {
            preCount = hrefCount / 2;
            nextCount = hrefCount / 2;
          }
          int val = (cpageInt - preCount) > 0 ? (cpageInt - preCount) : 1;
          int v1 = (cpageInt + nextCount) < totalInt ? (cpageInt + nextCount) : totalInt;
          if (v1 == totalInt) {
            val = totalInt - hrefCount + 1;
            val = (val <= 0 ? 1 : val); // 如果为负数，则修改为1
          } else if (val == 1 && v1 < totalInt) {
            v1 = totalInt > hrefCount ? hrefCount : totalInt;
          }

          // hrefCount个为一组显示
          for (int i = val; i <= v1; i++) {
            if (cpageInt == i) { // 当前页要加粗显示
              str.append(
                  "<span class='thx-page-span'><a class = 'on' href='#' >" + i + "</a></span>");
            } else {
              str.append("<span class='thx-page-span'  href='" + url + pageNoStr + i + "&perPage="
                  + perPage + perUrl + "'><a href='#' >" + i + "</a></span>");
            }
          }

          // 如果多于1组并且不是最后一组，显示“> >>”
          if (cpageInt < totalInt) {
            // >>：返回下一组最后一页
            // >：返回下一页
            str.append("<span class='thx-page-span'  href='" + url + pageNoStr + (cpageInt + 1)
                + "&perPage=" + perPage + perUrl + "'><a title='下一页' href='#'>></a></span>");
            str.append("<span class='thx-page-span'  href='" + url + pageNoStr + totalInt
                + "&perPage=" + perPage + perUrl + "'><a title='末页'  href='#'>>></a></span>");
          } else {
            str.append("<a  href='javascript:void(0);'>></a> ");
            str.append("<a  href='javascript:void(0);'>>></a> ");
          }
        }
      }
      str.append("</span>");
      writer.write(str.toString());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }

  public HttpServletRequest getRequest() {
    return request;
  }

  public void setRequest(HttpServletRequest request) {
    this.request = request;
  }

  public String getPageNo() {
    return pageNo;
  }

  public void setPageNo(String pageNo) {
    this.pageNo = pageNo;
  }

  public String getTotal() {
    return total;
  }

  public void setTotal(String total) {
    this.total = total;
  }

  public String getStyleClass() {
    return styleClass;
  }

  public void setStyleClass(String styleClass) {
    this.styleClass = styleClass;
  }

  public String getTheme() {
    return theme;
  }

  public void setTheme(String theme) {
    this.theme = theme;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUrlType() {
    return urlType;
  }

  public void setUrlType(String urlType) {
    this.urlType = urlType;
  }

  public int getHrefCount() {
    return hrefCount;
  }

  public void setHrefCount(int hrefCount) {
    this.hrefCount = hrefCount;
  }

  public boolean isHasPerPage() {
    return hasPerPage;
  }

  public void setHasPerPage(boolean hasPerPage) {
    this.hasPerPage = hasPerPage;
  }

  public boolean isHasGoto() {
    return hasGoto;
  }

  public void setHasGoto(boolean hasGoto) {
    this.hasGoto = hasGoto;
  }

}
